import React,{ Component } from 'react'
import {
    Collapse,
    Row,
    Col,
    Radio,
    Transfer,
    Button,
    message,
    Input,
} from 'antd';
import { LegionsProForm,LegionsProModal } from 'legions-pro-design';
import { bind,observer } from 'legions/store-react'
import ProjectStore from '../../stores/projectStore';
import { WrappedFormUtils } from 'legions-pro-design/es/interface/antd';
import { InstanceProForm } from 'legions-pro-design/es/LegionsProForm/interface';
import { InstanceProModal } from 'legions-pro-design/es/LegionsProModal/interface';
import { InstanceProTable } from 'legions-pro-design/es/LegionsProTable/interface';
import { observable,action,computed,runInAction } from 'mobx';
import { observableViewModel } from 'legions/store-utils'
import {
    PropertyColumnsConfigFormFields,
    PropertyTableDataSourceFormFieldsRule,
    PropertyTableDataSourceFormFields,
    PropertyTableBaseConfigFormFields,
} from '../../models/form/propertyFormModel';
import CodeEditor from '../../components/codeEditor';
import '../../assets/css/table-property.less';
const RadioGroup = Radio.Group;
import { TransferListProps } from 'antd/lib/transfer/list'
import { OperationEnum } from '../../constants/enum-data';
import * as recast from 'recast';
import TableListPropertyConfig,{ EditCodeEnum } from '../../components/property.config.table/tableListPropertyConfig';
import { transformCode } from 'legions-utils-ast/transform.format.code';
import { lazyInject } from 'legions-control-container'
import { tableAutoQueryEnumMapp,TableListViewDomain,TABLE_COLUMNS_ENUM_MAPP } from '../../services/components/tableListViewDomain';
import get from 'lodash/get';

interface IProps {
    store?: ProjectStore
}
const { Panel } = Collapse;
@bind({ store: ProjectStore })
@observer
export default class TableProperty extends Component<IProps> {
    @lazyInject(TableListPropertyConfig)
    tableListPropertyConfig!: TableListPropertyConfig
    errorMsg:string
    constructor(props: IProps) {
        super(props)
        const that = this;
        this.tableListPropertyConfig.registerInstance(that);
    }
    onEditColumns = () => {
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        if (TablePropertyApp.tableAutoQueryVM.sourceSelectedKeys.length > 1) {
            message.warning('单次只能编辑一行数据')
            return;
        }
        TablePropertyApp.tableAutoQueryVM.operationEnum = OperationEnum.EditTableColumns;

        TablePropertyApp.tablePropertyModalRef.viewModel.visible = true;
        // tslint:disable-next-line: no-magic-numbers
        TablePropertyApp.tablePropertyModalRef.viewModel.width = 560;
        TablePropertyApp.tablePropertyModalRef.viewModel.title = '编辑列信息';
        const item = TablePropertyApp.viewModel.tableColumns.find((item) => item.key === TablePropertyApp.tableAutoQueryVM.sourceSelectedKeys[0])
        const model = new PropertyColumnsConfigFormFields();
        model.columnsName.value = item.title as string;
        model.dataIndex.value = item.dataIndex;
        model.sorter.value = item.sorter as boolean;
        model.width.value = item.width.toString().replace('px','');
        model.customColumnsRender.value = get(item,'prorender');
        let timeId = setTimeout(() => {
            this.props.store.formProperyAddTableColumnsRef.store.updateFormInputData(this.props.store.formProperyAddTableColumnsRef.uid,model);
            this.props.store.formProperyAddTableColumnsRef.methods.setFormStates('dataIndex',(value) => {
                value.iFormProps['disabled'] = true;
            })
            clearTimeout(timeId);
        })
    }
    renderFooter = (props: TransferListProps) => {
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        if (props.titleText === '全部列') {
            return (
                <Button
                    disabled={TablePropertyApp.tableAutoQueryVM.sourceSelectedKeys.length ? false : true}
                    size="small"
                    style={{ float: 'right',margin: 5 }}
                    onClick={this.onEditColumns}
                >
                    编辑列
                </Button>
            );
        }
        return null
    }
    /** 查看列数据JSX结构渲染 */
    renderReadColumns() {
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        const targetKeys = (TablePropertyApp.viewModel.deletedTableColumns || []).map((item) => {
            return item.key
        }).slice()
        return <Transfer
            dataSource={TablePropertyApp.viewModel.transferShowColumns.map((item) => {
                return { key: item.key,title: item.title as string }
            })}
            titles={['全部列','移除列']}
            targetKeys={targetKeys}
            footer={this.renderFooter}
            onSelectChange={(sourceSelectedKeys,targetSelectedKeys) => {
                TablePropertyApp.tableAutoQueryVM.sourceSelectedKeys = sourceSelectedKeys;
            }}
            onChange={(nextTargetKeys,direction,moveKeys) => {
                if (direction === 'right') {
                    const deletedColumns = TablePropertyApp.viewModel.transferShowColumns.filter((item) => nextTargetKeys.includes(item.key.toString()))
                    const columns = TablePropertyApp.viewModel.transferShowColumns.filter((item) => !nextTargetKeys.includes(item.key.toString()))
                    TablePropertyApp.viewModel.tableColumns = columns.slice();
                    TablePropertyApp.viewModel.deletedTableColumns = [...TablePropertyApp.viewModel.deletedTableColumns || [],...deletedColumns]
                }
                if (direction === 'left') {
                    const deletedColumns = TablePropertyApp.viewModel.transferShowColumns.filter((item) => nextTargetKeys.includes(item.key.toString()))
                    TablePropertyApp.viewModel.deletedTableColumns = deletedColumns.slice();
                    const columns = TablePropertyApp.viewModel.transferShowColumns.filter((item) => !nextTargetKeys.includes(item.key.toString()))
                    const arr = [...TablePropertyApp.viewModel.tableColumns || [],...columns]
                    TablePropertyApp.viewModel.tableColumns = arr.filter((item,index) => {
                        return arr.indexOf(item) === index  // 去重
                    })
                }
            }}
            render={item => item.title}
        />
    }
    /** 重置表格列信息编辑表单状态(如被禁用项状态回归初始值,表单State数据置空) */
    resetTableColumnsFormState() {
        this.props.store.formProperyAddTableColumnsRef.store.updateFormInputData(this.props.store.formProperyAddTableColumnsRef.uid,new PropertyColumnsConfigFormFields());
        /** 恢复被禁用的表单项 */
        this.props.store.formProperyAddTableColumnsRef.methods.setFormStates('dataIndex',(value) => {
            value.iFormProps['disabled'] = false;
        })
    }
    /** 添加表格列表格 */
    renderAddTableColumns() {
        return <LegionsProForm
            <PropertyColumnsConfigFormFields>
            InputDataModel={PropertyColumnsConfigFormFields}
            mapPropsToFields={(props) => {
                return new PropertyColumnsConfigFormFields(props) // 实际处理结果实体
            }}
            onFieldsChange={(props,formFields) => {
                this.props.store.formProperyAddTableColumnsRef.store.updateFormInputData(this.props.store.formProperyAddTableColumnsRef.uid,formFields)
            }}
            onReady={(form,ref) => {
                this.props.store.formProperyAddTableColumnsRef = ref;
            }}
            colCount={1}
            controls={this.tableListPropertyConfig.createTableColumnsConfig()}
        ></LegionsProForm>
    }
   
    handleEditCode = (value: (typeof EditCodeEnum)[keyof typeof EditCodeEnum]) => {
        const viewModel: PropertyTableDataSourceFormFields = this.props.store.formProperyDataSourceRef.viewModel.InputDataModel as PropertyTableDataSourceFormFields;
        const valuesMapp = TableListViewDomain.tableAutoQuerystaticMember[tableAutoQueryEnumMapp[value]];
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        //@ts-ignore
        TablePropertyApp.tableAutoQueryVM.editConfigParameter = tableAutoQueryEnumMapp[value];
        TablePropertyApp.tablePropertyModalRef.viewModel.title = valuesMapp['label'];
        TablePropertyApp.tableAutoQueryVM.code = viewModel[tableAutoQueryEnumMapp[value]]['value'] || valuesMapp['value'];
        TablePropertyApp.tablePropertyModalRef.viewModel.visible = true;
        const width = 960;
        TablePropertyApp.tablePropertyModalRef.viewModel.width = width;
        TablePropertyApp.tableAutoQueryVM.operationEnum = OperationEnum.EditTableCode
    }
    /** 同步文本框代码值到表单组件元素项 */
    updateTableCodeValue(values: string) {
        const value = {};
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        const keys = EditCodeEnum[TablePropertyApp.tableAutoQueryVM.editConfigParameter];
        value[TablePropertyApp.tableAutoQueryVM.editConfigParameter] = { value: values };
        if (tableAutoQueryEnumMapp[keys]) {
            this.props.store.formProperyDataSourceRef.store.updateFormInputData(this.props.store.formProperyDataSourceRef.uid,value);
        }
        if (TABLE_COLUMNS_ENUM_MAPP[keys]) {/** 表格列配置数据 自定义列render 函数代码字符串 */
            this.props.store.formProperyAddTableColumnsRef.store.updateFormInputData(this.props.store.formProperyAddTableColumnsRef.uid,value);
        }
    }
    onEditOrAddColumns = () => {
        runInAction(() => {
            const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
            if (TablePropertyApp.tableAutoQueryVM.operationEnum === OperationEnum.addTableColumns) {
                this.props.store.formProperyAddTableColumnsRef.viewModel.form.validateFields((err,values: PropertyColumnsConfigFormFields) => {
                    const value = PropertyColumnsConfigFormFields.formFieldsToData(PropertyColumnsConfigFormFields,this.props.store.formProperyAddTableColumnsRef.viewModel.InputDataModel)
                    if (!err) {
                        if(TablePropertyApp.viewModel.tableColumns.filter((item)=>item.key === value['dataIndex']).length){
                            this.errorMsg = '属性名称已经存在，请重新设置'
                            message.warn(this.errorMsg)
                        }else{
                            // @ts-ignore
                            TablePropertyApp.viewModel.tableColumns.push({ ...value,key: value['dataIndex'] })
                            TablePropertyApp.viewModel.tableColumns = TablePropertyApp.viewModel.tableColumns.slice()
                            message.success('添加成功');
                            this.props.store.formProperyAddTableColumnsRef.store.updateFormInputData(this.props.store.formProperyAddTableColumnsRef.uid,new PropertyColumnsConfigFormFields())
                        }
                        console.log(TablePropertyApp.viewModel.tableColumns,'TablePropertyApp.viewModel.tableColumns');
                    }else{
                        this.errorMsg = '表单必填项为空'
                    }
                })
            }
            if (TablePropertyApp.tableAutoQueryVM.operationEnum === OperationEnum.EditTableColumns) {
                this.props.store.formProperyAddTableColumnsRef.viewModel.form.validateFields((err,values: PropertyColumnsConfigFormFields) => {
                    const value = PropertyColumnsConfigFormFields.formFieldsToData(PropertyColumnsConfigFormFields,this.props.store.formProperyAddTableColumnsRef.viewModel.InputDataModel)
                    if (!err) {
                        let index = TablePropertyApp.viewModel.tableColumns.findIndex((item) => item.dataIndex === value['dataIndex'])
                        if (index > -1) {
                            // @ts-ignore
                            TablePropertyApp.viewModel.tableColumns[index] = { ...value,key: value['dataIndex'] }
                            TablePropertyApp.viewModel.tableColumns = TablePropertyApp.viewModel.tableColumns.slice()
                            message.success('编辑成功');
                            TablePropertyApp.tablePropertyModalRef.viewModel.visible = false;
                            TablePropertyApp.tableAutoQueryVM.sourceSelectedKeys = [];
                            this.resetTableColumnsFormState();
                        }
                    }else {
                        this.errorMsg = '表单必填项为空'
                    }
                })
            }
        })

    }
    /** 对话框确定按钮 */
    private onOkModal = () => {
        //点击模态框确定按钮时清空错误信息
        this.errorMsg = ''
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        const operationEnum = TablePropertyApp.tableAutoQueryVM.operationEnum;
        if (operationEnum === OperationEnum.EditTableCode || operationEnum === OperationEnum.renderTableColumns) {
            const code = TablePropertyApp.tableAutoQueryVM.code;
            this.updateTableCodeValue(code);
        }
        else if (operationEnum === OperationEnum.EditTableColumns || operationEnum === OperationEnum.addTableColumns) {
            this.onEditOrAddColumns();
        }
        if (operationEnum === OperationEnum.renderTableColumns) {
            if (TablePropertyApp.tableAutoQueryVM.sourceSelectedKeys.length) {
                TablePropertyApp.tableAutoQueryVM.operationEnum = OperationEnum.EditTableColumns
            } else {
                TablePropertyApp.tableAutoQueryVM.operationEnum = OperationEnum.addTableColumns
            }
        }
        else {
            if(!this.errorMsg){
                TablePropertyApp.tablePropertyModalRef.viewModel.visible = false;
            }
        }
    }
    /** 渲染模态框内容区填入组件 */
    renderModalContent() {
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        const operationEnum = TablePropertyApp.tableAutoQueryVM.operationEnum;
        if (operationEnum === OperationEnum.EditTableCode || operationEnum === OperationEnum.renderTableColumns) {
            return <CodeEditor
                width="100%"
                height="300px"
                mode="typescript"
                value={TablePropertyApp.tableAutoQueryVM.code}
                onChange={(values: string) => {
                    this.updateTableCodeValue(values)
                    TablePropertyApp.tableAutoQueryVM.code = values
                }}
            ></CodeEditor>
        }
        else if (operationEnum === OperationEnum.addTableColumns || operationEnum === OperationEnum.EditTableColumns) {
            return this.renderAddTableColumns()
        }
        else if (operationEnum === OperationEnum.readTableColumns) {
            return this.renderReadColumns()
        }
        else {
            return null;
        }
    }
    render() {
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        return (
            <React.Fragment>
                <Collapse className="luban-table-property" defaultActiveKey={['1','2','3']}>
                    <Panel header="列属性" key="1">
                        <Row>
                            <Col span={5}><Button type="primary" onClick={() => {
                                TablePropertyApp.tableAutoQueryVM.operationEnum = OperationEnum.addTableColumns;
                                TablePropertyApp.tablePropertyModalRef.viewModel.visible = true;
                                TablePropertyApp.tablePropertyModalRef.viewModel.width = 560;
                                TablePropertyApp.tablePropertyModalRef.viewModel.title = '添加列数据';

                            }}>添加</Button></Col>
                            <Col span={5}> <Button onClick={() => {
                                TablePropertyApp.tableAutoQueryVM.operationEnum = OperationEnum.readTableColumns;
                                TablePropertyApp.viewModel.transferShowColumns = TablePropertyApp.viewModel.tableColumns.slice();
                                TablePropertyApp.tablePropertyModalRef.viewModel.visible = true;
                                TablePropertyApp.tablePropertyModalRef.viewModel.width = 560;
                                TablePropertyApp.tablePropertyModalRef.viewModel.title = '查看列数据';
                            }}>查看</Button></Col>
                        </Row>
                    </Panel>
                    <Panel header="基础配置" key="3">
                        <LegionsProForm
                            <PropertyTableBaseConfigFormFields>
                            InputDataModel={PropertyTableBaseConfigFormFields}
                            mapPropsToFields={(props) => {
                                return new PropertyTableBaseConfigFormFields(props) // 实际处理结果实体
                            }}
                            onFieldsChange={(props,formFields) => {
                                this.props.store.formProperyBaseConfigRef.store.updateFormInputData(this.props.store.formProperyBaseConfigRef.uid,formFields)
                            }}
                            onReady={(form,ref) => {
                                this.props.store.formProperyBaseConfigRef = ref;

                            }}
                            colCount={1}
                            controls={this.tableListPropertyConfig.createBaseConfig()}
                        ></LegionsProForm>
                    </Panel>
                    <Panel header="数据源" key="2">
                        <LegionsProForm
                            <PropertyTableDataSourceFormFields>
                            InputDataModel={PropertyTableDataSourceFormFields}
                            mapPropsToFields={(props) => {
                                ['parames','onReset','onSearch','token','model','transform','mappingEntity'].map((item) => {
                                    if (!props[item]['value']) {
                                        props[item]['value'] = TableListViewDomain.tableAutoQuerystaticMember[item]['value'];
                                    }
                                })
                                return new PropertyTableDataSourceFormFields(props) // 实际处理结果实体
                            }}
                            onFieldsChange={(props,formFields) => {
                                this.props.store.formProperyDataSourceRef.store.updateFormInputData(this.props.store.formProperyDataSourceRef.uid,formFields)
                            }}
                            onReady={(form,ref) => {
                                this.props.store.formProperyDataSourceRef = ref;
                            }}
                            colCount={1}
                            controls={this.tableListPropertyConfig.createDataSourceConfig()}
                        ></LegionsProForm>
                    </Panel>
                </Collapse>
                { /*  表格列配置属性自定义render函数设置及表格自定义托管参数代码设置start======= */}
                <LegionsProModal
                    closable={false}
                    maskClosable={false}
                    onOk={this.onOkModal}
                    onCancel={() => {
                        if(TablePropertyApp.tableAutoQueryVM.operationEnum === OperationEnum.renderTableColumns){
                            if (TablePropertyApp.tableAutoQueryVM.sourceSelectedKeys.length) {
                                TablePropertyApp.tableAutoQueryVM.operationEnum = OperationEnum.EditTableColumns
                            } else {
                                TablePropertyApp.tableAutoQueryVM.operationEnum = OperationEnum.addTableColumns
                            }
                            setTimeout(()=>{
                                TablePropertyApp.tablePropertyModalRef.viewModel.visible = true
                            },10)
                        }else{
                            if (OperationEnum.EditTableColumns === TablePropertyApp.tableAutoQueryVM.operationEnum) {
                                this.resetTableColumnsFormState();
                            }
                            TablePropertyApp.tableAutoQueryVM.operationEnum = null;
                        }
                    }}
                    onReady={(value) => {
                        TablePropertyApp.tablePropertyModalRef = value
                        // 表格其他属性代码设置模态框
                        const width = 960;
                        TablePropertyApp.tablePropertyModalRef.viewModel.width = width;
                    }}>
                    <React.Fragment>
                        {this.renderModalContent()}
                    </React.Fragment>
                </LegionsProModal>
                { /*  表格列配置属性自定义render函数设置end======= */}
            </React.Fragment>
        )
    }
}